#!/usr/local/bin/perl

use 5.010;
use DBI;

$database = "MarketDatabase";
$data_source = "DBI:Pg:dbname=$database";
$user_name = "jiro";
$db = DBI->connect( $data_source, $user_name ) or die $db->errstr;

# get table names 
$sql = "select relname from pg_stat_user_tables;";
$st = $db->prepare( $sql ) or dir $db>errstr;
$st->execute() or die $db->errstr;
while ( $table_name = $st->fetchrow_array() ) {
#    print $table_name . "\n";
    push( @table_names, $table_name );
}
$st->finish();

foreach $table_name ( @table_names ) {

#    print "processing $table_name\n";
    $class_name = $table_name;
    $class_name =~ s/_table//;

    $sql = "select column_name, data_type from information_schema.columns where table_catalog = '$database' and table_name='$table_name'";
    $st = $db->prepare( $sql ) or die $db->errstr;
    $st->execute() or die $db->errstr;
    $class_define =  "#import <Cocoa/Cocoa.h>\n\n";
    $class_define .= "\@interface $class_name : db_table_entry {\n\n";

    # get column info
    %columns = ();
    while ( ( $column_name, $type ) = $st->fetchrow_array() ) {

	given( $type ) {
	    when( "text" ) { $cocoa_type_name = "NSString*"; }
	    when( "real" ) { $cocoa_type_name = "double"; }
	    when( "timestamp with time zone" ) { $cocoa_type_name = "NSDate*"; }
	    when( "date" ) { $cocoa_type_name = "NSData*"; }
	    when( "double precision" ) { $cocoa_type_name = "double"; }
	    when( "integer" ) { $cocoa_type_name = "int"; }
	    when( "boolean" ) { $cocoa_type_name = "BOOL"; }
	    when( "character varying" ) { $cococa_type_name = "NSString*"; }
	    default { die "not given type '$type'"; }
	}
	$columns{ $column_name } = $cocoa_type_name;
    }

    #  member define
    while( ( $name, $type ) = each %columns ) {
	$class_define .= "\t" . $type . " " . $name . ";\n\n";
    }
    $class_define .= "}\n\n";

    # set member property
    while( ( $name, $type ) = each %columns ) {
	$class_define .= "\@property ( assign ) " . " " . $type . " " . $name . ";\n\n";
    }
    $class_define .= "\@end\n";

    $list_class_define = "@interface $table_name_list : db_entry_list {\n\n";
    $list_class_define .= "}\n\n";
    $list_class_define .= "+(id)listFromDb: (DbOperator*) dbOperator where: (Node*) condition;\n";
    $lint_class_define .= "-(id) initWithDbOperator: (DbOperator*) dbOperator;\n";
    $list_class_define .= "-(void) selectWhere: (Node*) condition;\n";
    $list_class_define .= "-(void) insert;\n";
    $list_class_define .= "-(void) updateColumns: (NSArray*) columnNames where: (Node*) condition;\n";
    $list_class_define .= "-(void) deleteWhere: (Node*) condition;\n";
    $list_calss_define .= "@end\n\n";

    open SOURCE_FILE, ">generated_files/$table_name.h" or die "file open failed, $!";
    print SOURCE_FILE $class_define;
    close SOURCE_FILE;
}
